import jwt
import time
from datetime import datetime, timedelta

from keep_project0 import settings


class MyJwt:
    def __init__(self):
        self.secret_key = settings.SECRET_KEY
        self.algorithm = 'HS256'
        self.expire_hours = 24  # token过期时间24小时
        self.refresh_expire_hours = 25   # refresh token过期时间25小时（比token多1小时）


    def encode(self, payload):  # 生成token
        """生成JWT token"""
        # 添加过期时间
        payload['exp'] = int(time.time()) + (self.expire_hours * 3600)
        payload['iat'] = int(time.time())  # 签发时间
        return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)

    # 刷新token
    def encode_refresh_token(self, payload):
        """生成refresh token"""
        # 复制payload，避免修改原对象
        refresh_payload = payload.copy()
        # 添加过期时间（比token多1小时）
        refresh_payload['exp'] = int(time.time()) + (self.refresh_expire_hours * 3600)
        refresh_payload['iat'] = int(time.time())  # 签发时间
        refresh_payload['type'] = 'refresh'  # 标记为refresh token
        return jwt.encode(refresh_payload, self.secret_key, algorithm=self.algorithm)

    def decode(self, token):   # 解析token
        """解析JWT token"""
        try:
            # 移除Bearer前缀（如果存在）
            if token.startswith('Bearer '):
                token = token[7:]

            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
            return payload
        except jwt.ExpiredSignatureError:
            print("JWT token已过期")
            return None
        except jwt.InvalidTokenError as e:
            print(f"JWT token无效: {e}")
            return None
        except Exception as e:
            print(f"JWT解析异常: {e}")
            return None

    def decode_refresh_token(self, token):
        """解析refresh token"""
        try:
            # 移除Bearer前缀（如果存在）
            if token.startswith('Bearer '):
                token = token[7:]
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])

            # 检查是否为refresh token
            if payload.get('type') != 'refresh':
                print("不是refresh token")
                return None

            return payload
        except jwt.ExpiredSignatureError:
            print("Refresh token已过期")
            return None
        except jwt.InvalidTokenError as e:
            print(f"Refresh token无效: {e}")
            return None
        except Exception as e:
            print(f"Refresh token解析异常: {e}")
            return None

    def is_expired(self, payload):
        """检查token是否过期"""
        if not payload or 'exp' not in payload:
            return True
        return payload['exp'] <= int(time.time())

    def is_refresh_token_expired(self, payload):
        """检查refresh token是否过期"""
        if not payload or 'exp' not in payload:
            return True
        return payload['exp'] <= int(time.time())


mjwt = MyJwt()